package com.tf_cut.admin.backend.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tf_cut.admin.backend.api.BackEndApi;
import com.tf_cut.admin.backend.vo.AgentCashOrderVo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.sys.sysauthority.service.SysAuthorityService;
import com.tf_cut.admin.sys.sysauthority.vo.SysAuthorityVo;
import com.tf_cut.admin.sys.sysuser.service.SysUserService;
import com.tf_cut.admin.sys.sysuser.vo.SysUserVo;
import com.tf_cut.admin.sys.sysuserauthority.service.SysUserAuthorityService;
import com.tf_cut.admin.sys.sysuserauthority.vo.SysUserAuthorityVo;
import com.tf_cut.admin.user.service.UserService;
import com.tf_cut.admin.util.AESPKCSUtil;
import com.tf_cut.admin.util.CacheUtil;
import com.tf_cut.admin.util.UUIDUtil;
import com.tf_cut.admin.util.VerifyCodeImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/backend/agent/mobile")
@Slf4j
public class AgentMobileController {


    @Autowired
    private BackEndApi backEndApi;

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private SysUserAuthorityService sysUserAuthorityService;

    @Autowired
    private SysAuthorityService sysAuthorityService;

    @Resource
    private AESPKCSUtil aESPKCSUtil;


    @RequestMapping("/getVerifyCodeImage")
    public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //设置页面不缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.getOutputStream();
        String verifyCode = VerifyCodeImageUtil.generateTextCode(VerifyCodeImageUtil.TYPE_NUM_UPPER, 4, null);
        String verifykey = request.getParameter("key");

        log.info("本次企业生成的验证码为：" + verifykey+":"+verifyCode );
        CacheUtil.put(verifykey, verifyCode);
        //设置输出的内容的类型为JPEG图像
        response.setContentType("image/jpeg");
        BufferedImage bufferedImage = VerifyCodeImageUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);
        //写给浏览器
        ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
    }

    @PostMapping("/login")
    public  Object login(@RequestBody  String json){


        JSONObject users = JSONObject.parseObject(json, JSONObject.class);

        String loginType = org.apache.commons.lang3.StringUtils.isNoneBlank(users.getString("loginType")) ? users.getString("loginType") : "2";
        String username = users.getString("username");
        Result<SysUserVo> byLoginName=null;
        SysUserVo sysUserVo=null;
        if("3".equalsIgnoreCase(loginType)){//微信获取手机号码一键登录
            String encryptedData = users.getString("encryptedData");
            String iv = users.getString("iv");
            String code = users.getString("code");
            String sessionKey = users.getString("sessionKey");
            //登录态失效才用code换取sessionKey
            if(sessionKey.equals("")){
                Map<String, Object> map=aESPKCSUtil.sessionKey(code);
                sessionKey = map.get("sessionKey")!=null ? map.get("sessionKey").toString() : "";
            }
            if( sessionKey.equals("")){
                return Result.of(null, false, "无法获取到微信数据【sessionKey】");
            }else{
                String str= AESPKCSUtil.decryptUserInfo(encryptedData,iv,sessionKey);
                JSONObject js=JSONObject.parseObject(str,JSONObject.class);
                if(js!=null && js.get("purePhoneNumber")!=null){
                    byLoginName = this.sysUserService.findByLoginName(js.get("purePhoneNumber").toString());
                    sysUserVo = byLoginName.getData();
                }else{
                    return Result.of(null, false, "无法获取到微信绑定的手机号码");
                }
            }
        }else{
            byLoginName = this.sysUserService.findByLoginName(username);
            sysUserVo = byLoginName.getData();
            if(!byLoginName.isFlag()||sysUserVo==null|| org.apache.commons.lang3.StringUtils.isBlank(sysUserVo.getLoginName())){
                return Result.of(null, false, "用户不存在");
            }
            if("1".equalsIgnoreCase(loginType)){
                //手机验证码登陆
                String verifyCode = users.getString("verifyCode");
                String code = CacheUtil.get(username);
                CacheUtil.delete(username);
                if(org.apache.commons.lang3.StringUtils.isBlank(code) || org.apache.commons.lang3.StringUtils.isBlank(verifyCode) ||
                        !code.equalsIgnoreCase(verifyCode)){
                    return Result.of(null, false, "验证码错误");
                }
            }else if("2".equalsIgnoreCase(loginType)){
                //账号密码登陆
                Boolean isverifycode=users.getBoolean("isverifycode");

                //判断验证码null，页面传过来的为null
                if(isverifycode==null){

                    String key = users.getString("key");
                    String s = CacheUtil.get(key);
                    String verifyCode = users.getString("verifyCode");
                    log.info("登录收到的key "+s+":"+verifyCode);
                    if(s==null||verifyCode==null||!s.equalsIgnoreCase(verifyCode)){
                        return Result.of(null, false, "验证码错误");
                    }
                }

                String password=users.getString("password");
                if(!sysUserVo.getPassword().equalsIgnoreCase(password)){
                    return Result.of(null, false, "密码错误");
                }
            }
        }

        //判断登录逻辑

        //登陆IP不在白名单
//        String ipAddr = IpUtil.getIpAddr(request);
//        String limitedIp = sysUserVo.getLimitedIp();
//        if(!StringUtils.isEmpty(limitedIp) && !Arrays.asList(limitedIp.split(",")).contains(ipAddr)){
//            msg = "{\"code\":\"400\",\"msg\":\"登陆IP不在白名单，请联系管理员\"}";
//            flag = true;
//        }

        //禁止多人在线
//        if("N".equals(sysUserVo.getLimitMultiLogin()) && allUserNameList.contains(sysUserVo.getLoginName())){
//            msg = "{\"code\":\"400\",\"msg\":\"该账号禁止多人在线，请联系管理员\"}";
//            flag = true;
//        }

        if(!byLoginName.isFlag()||sysUserVo==null|| org.apache.commons.lang3.StringUtils.isBlank(sysUserVo.getLoginName())){
            return Result.of(null, false, "用户不存在");
        }
        //超出有效时间
        if(!StringUtils.isEmpty(sysUserVo.getExpiredTime()) && new Date().getTime() > sysUserVo.getExpiredTime().getTime()){
            return Result.of(null, false, "该账号已失效，请联系管理员");

        }

        //禁止登陆系统
        if("N".equals(sysUserVo.getValid())){
            return Result.of(null, false, "该账号已被禁止登陆系统，请联系管理员");
        }

        String userId = sysUserVo.getUserId();

        //增加登陆者身份字段
        Map<String,String> authmap=new HashMap<>();
        List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(userId).getData();
        if(!sysUserAuthorityVoList.isEmpty()){
            SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(0);
            List<SysAuthorityVo> sysAuthorityVoList = sysAuthorityService.list(new SysAuthorityVo()).getData();
            for(SysAuthorityVo sysAuthorityVo:sysAuthorityVoList){
                if(sysAuthorityVo.getAuthorityId().equals(sysUserAuthorityVo.getAuthorityId())){
                    authmap.put("authorityName", sysAuthorityVo.getAuthorityName());
                    authmap.put("authorityRemark", sysAuthorityVo.getAuthorityRemark());
                    break;
                }

            }
        }else{
            authmap.put("authorityName", "");
            authmap.put("authorityRemark", "没有关联身份");
        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("data", new JSONObject());
        jsonObject.put("flag", true);

        //如果是代理商
        if(authmap.get("authorityName").equals("AGENT_USER")){

            String agentResult = agentInfoWithAgentId(userId);
            //如果是代理商 则替换
            jsonObject = JSONObject.parseObject(agentResult, JSONObject.class);
            if(StringUtils.isEmpty(jsonObject.getJSONObject("data").getString("agentId"))){
                return Result.of(null, false, "该账号不是代理商");
            }
        }


        JSONObject data= jsonObject.getJSONObject("data");

        String token = UUIDUtil.getUUID();
        CacheUtil.put(token,userId);
        data.put("token", token);
        data.put("userId", userId);
        data.put("loginId",sysUserVo.getUserId());
        data.put("loginName",sysUserVo.getLoginName());
        data.put("authorityName", authmap.get("authorityName"));
        data.put("authorityRemark", authmap.get("authorityRemark"));

        return  jsonObject;

    }

    @GetMapping("/getSmsCode")
    public Result getSmsCode(@RequestParam String mobile){
        log.debug("mobile:"+mobile);
        String code = backEndApi.getSmsCode(mobile);

        CacheUtil.put(mobile,code);
        //20201115:  修改了 Result.of("",true,"发送成功")
        return Result.of(""+code,true,"发送成功");
    }

    @PostMapping("/updatePassword")
    public  Result updatePassword(@RequestBody String json){

        JSONObject jsonObject = JSONObject.parseObject(json, JSONObject.class);
        String userId = jsonObject.getString("userId");
        String newpassword = jsonObject.getString("newpassword");
        String oldpassword = jsonObject.getString("oldpassword");
        Result<SysUserVo> result = Result.of(null,false,"修改失败，你输入的原密码错误！");

        SysUserVo sysUserVo = sysUserService.get(userId).getData();
        if(sysUserVo.getPassword().equalsIgnoreCase(oldpassword)){
            sysUserVo.setPassword(newpassword);
            result = sysUserService.save(sysUserVo);
            //置空隐私数据
            result.getData().setPassword(null);
        }

        return result;
    }


    @GetMapping("/logout")
    public  Result logout(@RequestParam String token){
        CacheUtil.delete(token);
        return  Result.of(null, true, "退出成功");
    }


   // @GetMapping("/agentInfoWithAgentId")
    private   String agentInfoWithAgentId(@RequestParam String loginId){
        JSONObject param=new JSONObject();
        param.put("loginId", loginId);
        String login = backEndApi.login(param.toJSONString());
        return login;

    }

    // 添加代理商
    @GetMapping("/home")
    public String home(@RequestParam("agentId") String agentId) {
        return backEndApi.home(agentId);
    }

    @GetMapping("/cash/withdrawallist")
    public  String withdrawallist(@RequestParam("agentId") String agentId,@RequestParam("startDate") String startDate,@RequestParam("endDate") String endDate) {
        return backEndApi.withdrawallist(agentId, startDate, endDate);

    }
    @PostMapping("/cash/withdrawalApply")
    public  String withdrawalApply(@RequestParam("token") String token, @RequestBody String json){
        AgentCashOrderVo agentCashOrder= JSON.parseObject(json,AgentCashOrderVo.class);
        //获取用户流水号
        String userId=CacheUtil.get(token);
        Result<SysUserVo> result=sysUserService.get(userId);
        agentCashOrder.setOrderId(result.getData().getMerchantNumber());
        return  backEndApi.withdrawalApply(JSON.toJSONString(agentCashOrder));
    }

    /**
     * 查询银行bankcode
     * @return
     */
    @GetMapping("/cash/bankcodelist")
    public  String bankcodelist(){
        return backEndApi.bankcodelist();
    }

    /**
     * 查询所属账号
     * @return
     */
    @GetMapping("/cash/accountBankList")
    public  String accountBankList(@RequestParam("agentId") String agentId){
        return backEndApi.accountBankList(agentId);
    }

    /**
     * 添加银行卡
     * @param
     * @return
     */
    @PostMapping("/cash/insertAccountBank")
    public  String insertAccountBank(@RequestBody String json) {
        return backEndApi.insertAccountBank(json);
    }

    /**
     * 查询收益
     * @return
     */
    @GetMapping("/cash/agentCommionInfo")
    public  String agentCommionInfo(@RequestParam("agentId") String agentId){
        return backEndApi.agentCommionInfo(agentId);
    }

    @GetMapping("/cash/findCommionInfolist")
    public  String findCommionInfolist(@RequestParam("agentId") String agentId, @RequestParam("startDate") String startDate,
                                       @RequestParam("endDate") String endDate, @RequestParam("paySubject") String paySubject){
        return backEndApi.findCommionInfolist(agentId, startDate, endDate, paySubject);
    }


    @GetMapping("/cash/findProfitlist")
    public String findProfitlist(@RequestParam("agentId") String agentId, @RequestParam("operType") Integer operType,
                                                              @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate){
        return backEndApi.findProfitlist(agentId, operType,startDate,endDate);
    }


    // 根据代理商查商户
    @GetMapping("/seller/sellerlistWithAgentId")
    public String findListSeller(@RequestParam String agentId, @RequestParam(required = false) String agentName,@RequestParam(defaultValue = "1") int page,
                                                               @RequestParam(defaultValue = "10") int rows) {
        return backEndApi.findListSeller(agentId, agentName,page, rows);
    }

    // 根据代理商查商户
    @GetMapping("/seller/sellerDetail")
    public String sellerDetail(@RequestParam("sellerId") String sellerId) {
        return backEndApi.sellerDetail(sellerId);
    }

    @GetMapping(value = "/seller/findsellerWithAgentId")
    public String findsellerWithAgentId(@RequestParam("agentId") String agentId){
        return  backEndApi.findsellerWithAgentId(agentId);
    }

    @PostMapping(value = "/seller/sellerAmountWithAgentId")
    public String sellerAmountWithAgentId(@RequestBody String json){
        return backEndApi.sellerAmountWithAgentId(json);
    }

    @PostMapping("/seller/sellerProviderDay")
    public String sellerProviderDay(@RequestBody String json) {
        return  backEndApi.sellerProviderDay(json);
    }

    @PostMapping("/seller/sellerProviderMonth")
    public String sellerProviderMonth(@RequestBody String json) {
        return backEndApi.sellerProviderMonth(json);
    }



}
